package com.thti.mecool.client.activity;

import java.io.File;
import java.util.Date;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.thti.mecool.client.base.BaseActivity;
import com.thti.mecool.client.base.Cache;
import com.thti.mecool.client.util.DownloadProgressListener;
import com.thti.mecool.client.util.FileDownloader;
import com.thti.mecool.client.util.StringUtil;
import com.thti.mecool.client.util.Util;



public class UpdateActivity extends BaseActivity {

	public ProgressDialog pBar;
	private ProgressBar progressBar;
	private TextView bartext;
	private static final int DOWNLOAD_FLAG = 1;
	private String updateUrl = "";
	String fileName = null;
	private Button update_app, cancel_app;
	private TextView update_message;
	PowerManager.WakeLock wakeLock;  
	public static boolean flag =true;
	String fileNameDetail;
	SharedPreferences save_FileInfo;
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (!Thread.currentThread().isInterrupted()) {
				switch (msg.what) {
				case DOWNLOAD_FLAG:
						int size = msg.getData().getInt("size");
						progressBar.setProgress(size);

						int result = (int) ((float) size
								/ (float) progressBar.getMax() * 100);
						bartext.setText(result + "%");
						if (result == 100) {
							Toast.makeText(UpdateActivity.this,
									getString(R.string.update_down_msg), 0).show();
							UpdateActivity.this.finish();
//							((WelCome)ContextCache.getmContext()).finish();
							update();
						}
					break;

				default:
					break;
				}

			}
			super.handleMessage(msg);
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.update);
		//ActivityCache.add(this);
		Cache.add(this);
		Intent intent = getIntent();
		updateUrl = intent.getStringExtra("updateUrl");
		String info=intent.getStringExtra("info");
		update_app = (Button) findViewById(R.id.update_app);
		cancel_app = (Button) findViewById(R.id.cancel_app);
		update_message = (TextView) findViewById(R.id.update_message);
		save_FileInfo = getSharedPreferences("FilePreferences", 0);
//		update_message
//				.setText(Html
//						.fromHtml(info));
		Log.v("升级信息:", info);
		if(!StringUtil.isNotBlank(info)){
			update_message.setText(Html.fromHtml("<h2>升级版本10.8.8.8\n</h2>"));
		}else{
			try {
				update_message
				.setText(Html
						.fromHtml(info));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		// progressBar.setVisibility(View.GONE);
		update_app.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				UpdateActivity.this.setTitle("正在努力下载中...");
				update_app.setEnabled(false);
				update_message.setVisibility(View.GONE);
				progressBar = (ProgressBar) findViewById(R.id.progressBar);
				progressBar.setVisibility(View.VISIBLE);
				bartext = (TextView) findViewById(R.id.bartext);			
				if (Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)) {
					if(StringUtil.isBlank(save_FileInfo.getString("filename", null))){
						fileName = String.valueOf(new Date().getTime()) + ".apk";
					}else{
						fileName=save_FileInfo.getString("filename", null);	
					}	
					Util.print("fileName>>>>>>>>>>"+fileName);
					download(updateUrl,
							Environment.getExternalStorageDirectory(), fileName);

				} else if(Environment.getExternalStorageState().equals(Environment.MEDIA_REMOVED)){
					if(StringUtil.isBlank(save_FileInfo.getString("filename", null))){
						fileName = String.valueOf(new Date().getTime()) + ".apk";
					}else{
						fileName=save_FileInfo.getString("filename", null);	
					}
					File dir = getDir("apk", Context.MODE_PRIVATE | Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE); 

					download(updateUrl,
							dir, fileName);
		        }
//				cancel_app.setText("下次下载");
			}
		});
		cancel_app.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				AlertDialog.Builder builder = new Builder(UpdateActivity.this);
//				builder.setMessage("确定要取消吗？");
//				builder.setTitle("提示");
//				builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//					@Override
//					public void onClick(DialogInterface dialog, int which) {
//						dialog.dismiss();
//						if (Environment.getExternalStorageState().equals(
//								Environment.MEDIA_MOUNTED)) {
//							fileNameDetail="/sdcard/" + fileName;
//						}else{
//							fileNameDetail=getFilesDir() + "/" + fileName;
//						}
//						File fileApk=new File(fileNameDetail);
//						if(fileApk.exists()){
//							fileApk.delete();
//						}
						Editor save_editor = save_FileInfo.edit();
						save_editor.putString("filename", fileName);
						save_editor.commit();
						flag = false;
						exitApp();
						System.exit(0);
//					}
//				});
//				builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
//					@Override
//					public void onClick(DialogInterface dialog, int which) {
//						dialog.dismiss();
//					}
//				});
//				builder.create().show();
				
			}
		});

	}
	
    @Override
	protected void onResume()
	{
		super.onResume();

		//启用屏幕常亮  
		wakeLock = ((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "UpdateActivity");  
		wakeLock.acquire(); 
	}

	protected void download(final String path, final File savedir,
			final String fileName) {
		new Thread(new Runnable() {
			@Override
			public void run() {

				try {
						FileDownloader downloader = new FileDownloader(
								UpdateActivity.this, path, savedir, 3, fileName);
						progressBar.setMax(downloader.getFileSize());// 设置进度条的最大刻度为文件的总大小
						downloader.download(new DownloadProgressListener() {
							@Override
							public void onDownloadSize(int size) {
								Message msg = new Message();
								Bundle data = new Bundle();
								msg.what = DOWNLOAD_FLAG;
								data.putInt("size", size);
								data.putInt("isfinish", size);
								msg.setData(data);
								handler.sendMessage(msg);

							}
						});
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();

	}

	void update() {
		Intent intent=null;
		String fileNameDetail = null;;
		try {
			intent = new Intent(Intent.ACTION_VIEW);
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				intent.setDataAndType(
						Uri.fromFile(new File("/sdcard/" + fileName)),
						"application/vnd.android.package-archive");
				fileNameDetail="/sdcard/" + fileName;
			} else {
				intent.setDataAndType(
						Uri.fromFile(new File(getFilesDir() + "/" + fileName)),
						"application/vnd.android.package-archive");
				fileNameDetail=getFilesDir() + "/" + fileName;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		SharedPreferences save_LoginInfo = getSharedPreferences("UpdatePreferences", 0);
		Editor save_editor = save_LoginInfo.edit();
		save_editor.putString("path", fileNameDetail);
		save_editor.commit();
		
		Editor file_editor = save_FileInfo.edit();
		file_editor.putString("filename", null);
		file_editor.commit();
		startActivity(intent);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return false;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		handler=null;
	}
	
	


}